using System;
using System.Collections.Generic;
using PersonMgrApp.Interfaces;

namespace PersonMgrApp.Implementations
{
    public class PersonMgr : IPersonMgr
    {
        private readonly IConfiguration _configuration;
        private readonly IDataAccessLayer _dataAccessLayer;

        private readonly Object _lockObj = new Object();
        private readonly TimeSpan _cacheRefreshInterval;
        private DateTime _lastCacheRefreshTime = DateTime.MinValue;
        private Dictionary<string, int> _cachedPeople;

        public PersonMgr(IConfiguration configuration, IDataAccessLayer dataAccessLayer)
        {
            _configuration = configuration;
            _dataAccessLayer = dataAccessLayer;
            _cacheRefreshInterval = new TimeSpan(0, 0, 0, _configuration.CacheRefreshInterval);
        }

        public int GetPersonAge(string name)
        {
            lock (_lockObj)
            {
                CheckRefresh();

                int age;
                if (!_cachedPeople.TryGetValue(name, out age))
                {
                    age = -1;
                }
                return age;
            }
        }

        public void CheckRefresh()
        {
            lock (_lockObj)
            {
                if (DateTime.Now - _cacheRefreshInterval > _lastCacheRefreshTime)
                {
                    Refresh();
                }
            }
        }

        public void Refresh()
        {
            lock (_lockObj)
            {
                _cachedPeople = _dataAccessLayer.GetPersonAges();
                _lastCacheRefreshTime = DateTime.Now;
            }
        }
    }
}